package com.proyecto.robomind.game;

import com.proyecto.robomind.R;
import com.proyecto.robomind.interpreter.FileManager;
import com.proyecto.robomind.map.MapHandler;
import com.proyecto.robomind.model.MapSquare;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class GameLayout extends Activity{
	
	private EditText mTitleText;
    private EditText mBodyText;
    private boolean recentlyTyped = false;
    private Long mRowId;
    private Long wantedId;
    
    private Long mapId;
    private boolean mapLoaded;
    
    private FileManager mDbHelper;
    
    private LinearLayout panelLayout;
    private MainGamePanel gamePanel;

	ImageButton pauseBtn;
	ImageButton playBtn;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        mDbHelper = new FileManager(this.getApplicationContext());
        mDbHelper.open();
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);  
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        
        setContentView(R.layout.main_game_layout); 
        
        mapLoaded = false;
        
        pauseBtn = (ImageButton) findViewById(R.id.pauseScriptBtn);
    	playBtn = (ImageButton) findViewById(R.id.playScriptBtn);
        
        mTitleText = (EditText) findViewById(R.id.title);
        mTitleText.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            	recentlyTyped = true;
            } 
        });
        mBodyText = (EditText) findViewById(R.id.body);
        mBodyText.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            	recentlyTyped = true;
            } 
        });
        
        mRowId = (savedInstanceState == null) ? null :(Long) savedInstanceState.getSerializable(FileManager.KEY_ROWID);
		if (mRowId == null) {
			Bundle extras = getIntent().getExtras();
			mRowId = extras != null ? extras.getLong(FileManager.KEY_ROWID) : null;
		}
		
		populateFields();
		
		panelLayout = (LinearLayout) findViewById(R.id.gamePanelLayout);
		gamePanel = new MainGamePanel(this.getApplicationContext());
		panelLayout.addView(gamePanel);		
    }
	
	public void loadScript(View v){
		createScriptDialog();
	}
	
	public void saveScript(View v){
		saveState();
		Toast.makeText(this, "Script saved succesfully",Toast.LENGTH_SHORT).show();
	}
	
	public void loadMap(View v){
		createMapDialog();
	}
	
	public void newScript(View v){
		if(recentlyTyped){
		    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		    alertDialog.setMessage("You did not save your progress. Do you wish to save it?");
		    alertDialog.setButton3("Cancel", new DialogInterface.OnClickListener() {
		    	public void onClick(DialogInterface dialog, int which) {
		    		dialog.dismiss();
		    } });
		    alertDialog.setButton2("No", new DialogInterface.OnClickListener() {
		    	public void onClick(DialogInterface dialog, int which) {
		    		dialog.dismiss();
		    		mRowId = null;
		    		populateFields();
		    		recentlyTyped = false;
		    } });
		    alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
		    	public void onClick(DialogInterface dialog, int which) {
		    		dialog.dismiss();
		    		saveState();
		    		mRowId = null;
		    		populateFields();
		    		recentlyTyped = false;
		    } });
		    alertDialog.show();
		}else{
			mRowId = null;
			populateFields();
    		recentlyTyped = false;
		}
	}
	
	public void runScript(View v){
		if(v.getId()== R.id.playScriptBtn){
			playScript();
		}else if(v.getId() == R.id.pauseScriptBtn){
			pauseScript();
		}
	}
	
	public void playScript(){
		if(mapLoaded){
			playBtn.setVisibility(View.INVISIBLE);
			pauseBtn.setVisibility(View.VISIBLE);
			gamePanel.setScript(mBodyText.getEditableText().toString());
			gamePanel.setThreadRunning(true);
		}else{
			createMapDialog();
		}
	}
	
	public void pauseScript(){
		gamePanel.setThreadRunning(false);
		playBtn.setVisibility(View.VISIBLE);
		pauseBtn.setVisibility(View.INVISIBLE);
	}
	
    private void populateFields() {
        if (mRowId != null) {
            Cursor note = mDbHelper.fetchNote(mRowId);
            startManagingCursor(note);
            mTitleText.setText(note.getString(
                    note.getColumnIndexOrThrow(FileManager.KEY_TITLE)));
            mBodyText.setText(note.getString(
                    note.getColumnIndexOrThrow(FileManager.KEY_BODY)));
        }else{
        	mTitleText.setText("");
        	mBodyText.setText("");
        }
    }
    
    private void populateFields(Long mRowId) {
        if (mRowId != null) {
            Cursor note = mDbHelper.fetchNote(mRowId);
            startManagingCursor(note);
            mTitleText.setText(note.getString(
                    note.getColumnIndexOrThrow(FileManager.KEY_TITLE)));
            mBodyText.setText(note.getString(
                    note.getColumnIndexOrThrow(FileManager.KEY_BODY)));
        }else{
        	mTitleText.setText("");
        	mBodyText.setText("");
        }
    }
    
    public void loadMap(Long mapId){
    	if (mapId != null) {
            Cursor map = mDbHelper.fetchMap(mapId);
            startManagingCursor(map);
            
            MapSquare[][] ms = MapHandler.concatenizeMap(map.getString(map.getColumnIndexOrThrow(FileManager.KEY_MAP)),panelLayout.getHeight(), panelLayout.getWidth());
            
            gamePanel.loadMap(ms, map.getString(map.getColumnIndexOrThrow(FileManager.KEY_TITLE)));

        	mapLoaded = true;
    	}
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        saveState();
        outState.putSerializable(FileManager.KEY_ROWID, mRowId);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mRowId!=null)
        	saveState();
        pauseScript();
    }

    @Override
    protected void onResume() {
        super.onResume();
        populateFields();
    }
    
    private void saveState() {
        String title = mTitleText.getText().toString();
        String body = mBodyText.getText().toString();

        if(title.equals("")){
        	title = "No title";
        }

        if (mRowId == null) {
            long id = mDbHelper.createNote(title, body);
            if (id > 0) {
                mRowId = id;
            }
        } else {
            mDbHelper.updateNote(mRowId, title, body);
        }
		recentlyTyped = false;
    }
    
    public ListView fillScriptList(){
    	 Cursor notesCursor = mDbHelper.fetchAllNotes();
         startManagingCursor(notesCursor);

         String[] from = new String[]{FileManager.KEY_TITLE};
         int[] to = new int[]{R.id.text1};

         SimpleCursorAdapter notes = 
             new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
         ListView lv = new ListView(this);
         lv.setAdapter(notes);
         lv.setBackgroundColor(Color.WHITE);
         return lv;
    }
    
	public void createScriptDialog(){
		wantedId = null;
	    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
	    alertDialog.setView(createScriptList());
	    alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int which) {
	    		dialog.dismiss();
	    		wantedId = null;
	    } });
	    alertDialog.setButton3("Delete", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int which) {
	    		if(wantedId != null){
		    		dialog.dismiss();
		    		mDbHelper.deleteNote(wantedId);
		    		if(wantedId == mRowId)
		    			mRowId = null;
		    		wantedId = null;
	    		}	    		
	    } });
	    alertDialog.setButton("Load", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int which) {
	    		if(wantedId != null){
		    		dialog.dismiss();
		    		populateFields(wantedId);
		    		mRowId = wantedId;
		    		wantedId =null;
	    		}
	    } });
	    alertDialog.show();
	}
	
	public ListView createScriptList(){
		ListView modeList = fillScriptList();
		modeList.setBackgroundColor(Color.WHITE);
	    modeList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				wantedId = id;
			}
		});
	    return modeList;
	}
	
	public ListView fillMapList(){
		Cursor notesCursor = mDbHelper.fetchAllMaps();
        startManagingCursor(notesCursor);

        String[] from = new String[]{FileManager.KEY_TITLE};
        int[] to = new int[]{R.id.text1};

        SimpleCursorAdapter notes = 
            new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
        ListView lv = new ListView(this);
        lv.setAdapter(notes);
        lv.setBackgroundColor(Color.WHITE);
        return lv;
   }
   
	public void createMapDialog(){
		mapId = null;
	    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
	    alertDialog.setView(createMapList());
	    alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int which) {
	    		dialog.dismiss();
	    } });

	    alertDialog.setButton("Load", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int which) {
	    		if(mapId != null){
	    			dialog.dismiss();
	    			loadMap(mapId);
	    		}
	    } });
	    alertDialog.show();
	}
	
	public ListView createMapList(){
		ListView modeList = fillMapList();
		modeList.setBackgroundColor(Color.WHITE);
	    modeList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				mapId = id;
			}
		});
	    return modeList;
	}
	
}
